package net.aiion.weave.impl.resources.provider;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import net.aiion.weave.impl.resources.ResourceImpl;
import net.aiion.weave.spi.resources.Resource;
import net.aiion.weave.spi.resources.ResourceException;
import net.aiion.weave.spi.resources.provider.ResourceProvider;

public class FileResourceProvider implements ResourceProvider
{
    private File classpathDirectory;

    public FileResourceProvider(final File aClasspathDirectory) {
        classpathDirectory = aClasspathDirectory;
    }

    @Override
    public Iterator<Resource> iterator() {
        return loadResources().iterator();
    }

    private Collection<Resource> loadResources() {
        try {
            return Collections.unmodifiableCollection(loadResources(classpathDirectory));
        } catch (final MalformedURLException e) {
            throw new ResourceException(e);
        }
    }

    private Collection<Resource> loadResources(final File aDirectory) throws MalformedURLException {
        final Collection<Resource> resources = new ArrayList<>();
        for (File f : aDirectory.listFiles()) {
            if (f.isDirectory()) {
                resources.addAll(loadResources(f));
            } else {
                resources.add(new ResourceImpl(f.getAbsolutePath().substring(
                    classpathDirectory.getAbsolutePath().length() + 1), new URL("file:" + f.getAbsolutePath())));
            }
        }
        return resources;
    }
}
